// pages/index/index.js

Page({
  data: {
    recommendedWordBooks: [],
    myWordBooks: [],
    searchQuery: ''
  },

  onLoad: function() {
    const app = getApp();
    this.setData({
      recommendedWordBooks: app.globalData.wordbooks.filter(book => book.id <= 3),
      myWordBooks: app.globalData.wordbooks.filter(book => book.id === 4)
    });
  },

  // 过滤搜索单词本
  filterWordBooks(query) {
    const app = getApp();
    const wordbooks = app.globalData.wordbooks;
    if (!query) {
      return {
        recommended: wordbooks.filter(book => book.id <= 3),
        my: wordbooks.filter(book => book.id === 4)
      };
    }

    const lowerQuery = query.toLowerCase();
    return {
      recommended: wordbooks
        .filter(book => book.id <= 3)
        .filter(book => book.title.toLowerCase().includes(lowerQuery) || book.description.toLowerCase().includes(lowerQuery)),
      my: wordbooks
        .filter(book => book.id === 4)
        .filter(book => book.title.toLowerCase().includes(lowerQuery) || book.description.toLowerCase().includes(lowerQuery))
    };
  },

  // 搜索单词本
  searchWordBook(e) {
    const query = e.detail.value;
    const { recommended, my } = this.filterWordBooks(query);

    this.setData({
      searchQuery: query,
      recommendedWordBooks: recommended,
      myWordBooks: my
    });
  },

  // 重置搜索
  resetSearch() {
    const app = getApp();
    const wordbooks = app.globalData.wordbooks;
    this.setData({
      searchQuery: '',
      recommendedWordBooks: wordbooks.filter(book => book.id <= 3),
      myWordBooks: wordbooks.filter(book => book.id === 4)
    });
  },



  // 选择单词本
  selectWordBook(e) {
    const id = e.currentTarget.dataset.id
    const wordBook = [...this.data.recommendedWordBooks, ...this.data.myWordBooks].find(item => item.id === id)

    if (wordBook) {
      // 存储当前选中的单词本
      const app = getApp()
      app.globalData.currentWordBook = wordBook

      // 跳转到学习页面
      wx.navigateTo({
        url: '/pages/learn/learn'
      })
    }
  },

  // 查看全部推荐单词本
  viewAllRecommended() {
    wx.navigateTo({
      url: '/pages/wordbooks/wordbooks?type=recommended'
    })
  },

  // 管理我的单词本
  manageMyWordBooks() {
    wx.navigateTo({
      url: '/pages/wordbooks/wordbooks?type=my'
    })
  },

  onShow: function () {
    // 页面显示时刷新数据
    const app = getApp()
    if (app.globalData.userProgress) {
      // 更新学习进度
      this.setData({
        'myWordBooks[0].progress': app.globalData.userProgress.progress || 65
      })
    }
  }
})